<template>
  <div>
    <el-form label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spu.tmId" placeholder="请选择品牌">
          <el-option :label="mark.tmName" :value="mark.id" v-for="mark in marklist" :key="mark.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" v-model="spu.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <!--
          action 图片上传地址 
          list-type:文件列表类型
          on-preview:图片预览
          on-remove：删除图片触发
          file-list：图片上传列表
        -->
        <el-upload
          action="/product-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handlesuccess"
          :file-list='spuImageList'
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
           <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unSelectattr.length}个未选择`" v-model="attrIdandName">
          <el-option :label="saleattr.name" :value="`${saleattr.id}:${saleattr.name}`" v-for="saleattr in unSelectattr" :key="saleattr.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" @click="addAttr" :disabled="!attrIdandName">添加销售属性</el-button>

        <el-table border :data="spu.spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            align="center"
          ></el-table-column>
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值名称列表" prop=''>
            <!-- closable x的按钮-->
            <template slot-scope="{row}">
               <!-- el-tag是展示属性值列表数据 -->
              <el-tag style="margin:10px"
              :key="tag.id" v-for="(tag,index) in row.spuSaleAttrValueList" closable
                :disable-transitions="false" @close="handleClose(row,index)">
                {{tag.saleAttrValueName}}
              </el-tag>
              <!-- 下面是input框和button的切换 -->
              <el-input class="input-new-tag"  v-if="row.inputVisible"  v-model="row.inputValue" 
               ref="saveTagInput"  size="mini" @keyup.enter.native="$event.target.blur()" 
               @blur="handleInputConfirm(row)">
             </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" >
            <template slot-scope="{row,$index}">
              <el-button type="danger" icon="el-icon-delete" @click="deleteAttr(row,$index)"></el-button>
            </template>
          
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="AddandUpdatespu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
       dynamicTags: ['标签一', '标签二', '标签三'],
       
       dialogVisible: false,
       dialogImageUrl: '',
       attrIdandName:'',//收集未选择销售属性id
      //存储spu信息(里面到字段来自文档是需要带给服务器的)
      spu:{
       
     "category3Id": 0,
     "description": "",
     "spuName": "",
     "tmId": null,//品牌id
     "spuImageList": [
    // {
    //   "id": 0,
    //   "imgName": "string",
    //   "imgUrl": "string",
    //   "spuId": 0
    // }
  ],

  "spuSaleAttrList": [
    // {
    //   "baseSaleAttrId": 0,
    //   "id": 0,
    //   "saleAttrName": "string",
    //   "spuId": 0,
    //   "spuSaleAttrValueList": [
    //     {
    //       "baseSaleAttrId": 0,
    //       "id": 0,
    //       "isChecked": "string",
    //       "saleAttrName": "string",
    //       "saleAttrValueName": "string",
    //       "spuId": 0
    //     }
    //   ]
    // }
  ],
 
}, 
      marklist:[], //存储品牌信息
      chooseMark:'',//选择的品牌
      spuImageList:[], //存储图片信息
      saleAttrList:[], //存储销售属性信息
    };
  },
  methods: {
    //照片墙删除某个图片时触发
    handleRemove(file, fileList) {
     console.log(file,fileList)
    },
    //照片墙预览时触发
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片上传成功时触发
    handlesuccess(response,file,fileList){
      this.spuImageList=fileList
    },
    //点击取消按钮
    cancel() {
      this.$emit("changescene", 0);
      //清理数据
      Object.assign(this._data,this.$options.data())
    },
    async getSpuList(row) {
      console.log(row)
      //1.获取spu信息
      if(row.id){
      let spuResult = await this.$API.spu.reqGetspu(row.id);
      if (spuResult.code === 200) {
        this.spu = spuResult.data;
      }
      }else{
        this.spu.category3Id=row
      }
      
      //2.获取品牌信息
      let markResult = await this.$API.spu.reqGetTraddemark();
      if (markResult.code === 200) {
        this.marklist = markResult.data;
      }
      //3.获取图片信息
       if(row.id){
      let imageResult = await this.$API.spu.reqGetImage(row.id);
      if (imageResult.code === 200) {
        const ImageListarr = imageResult.data;
        //照片墙展示必须需要name和url字段，所以需要给它添加
        ImageListarr.forEach(item => {
          item.name=item.imgName
          item.url=item.imgUrl
        });
        //将整理好数据赋值
        this.spuImageList=ImageListarr
      }
      }
      //4.获取销售属性信息
      let saleAttrResult = await this.$API.spu.reqbaseAttr();
      if (saleAttrResult.code === 200) {
        this.saleAttrList = saleAttrResult.data;
      }
    },
    //5.添加销售属性
    addAttr(){
    const [id,name]= this.attrIdandName.split(':')
      this.spu.spuSaleAttrList.push({
        baseSaleAttrId:id,
        saleAttrName:name,
        spuSaleAttrValueList:[]
      })
      this.attrIdandName=''
    },
    //6.控制input和button的显示和隐藏
    showInput(row) {
        //动态给每个数据添加
        this.$set(row,'inputVisible',true)
        this.$set(row,'inputValue','')
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
     //7.添加销售属性对应属性值（失去焦点）
      handleInputConfirm(row) {
        let inputValue = row.inputValue;
        if (!inputValue.trim()) return alert("值不能为空！")
        else{
          let result=row.spuSaleAttrValueList.some(item=>item.saleAttrValueName===inputValue)
          if(result) {
             return alert("该属性值已经存在！")
            }else{
           row.spuSaleAttrValueList.push({
           baseSaleAttrId:row.baseSaleAttrId,
           saleAttrValueName:inputValue,
           saleAttrName:row.saleAttrName,
          });
            row.inputVisible = false
            row.inputValue = ''
            }
           }
        },
    // 8.删除销售属性对应属性值
    handleClose(row,index) {
        row.spuSaleAttrValueList.splice(index,1)
        },
     // 9.删除销售属性
    deleteAttr(row,$index){
       this.spu.spuSaleAttrList.splice($index,1)
        },
      //10.添加/修改spu信息
    async AddandUpdatespu(){
         //整理图片数据
        this.spu.spuImageList=this.spuImageList.map(item=>{ return{
          imageName:item.name,
          imgUrl:item.response?item.response.data:item.url
         }
         })

      if(this.spu.id){
        const updateresult=await this.$API.spu.reqAddandUpdatespu(this.spu)
        if(updateresult.code==200){
          this.$message({message:'修改信息成功！',type:'success'})
          this.$emit('changescene',0)
        }else{
          this.$message({message:'修改信息失败！'})
        }
      }else{
        const addresult=await this.$API.spu.reqAddandUpdatespu(this.spu)
        console.log(addresult)
         if(addresult.code==200){
          this.$message({message:'添加信息成功！',type:'success'})
           this.$emit('changescene',0)
           //去指定页数
           this.$emit('gopage',1)
        }else{
          this.$message({message:'添加信息失败！'})
        }
      }
      Object.assign(this._data,this.$options.data())
      }
      },

  //计算出未选择的销售属性信息
  computed:{
    unSelectattr(){
 return this.saleAttrList.filter(item=>{
  return this.spu.spuSaleAttrList.every(item1=>{
    return item1.saleAttrName!==item.name
       })
     })
    }
  }
};
</script>

<style>
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
